import smtplib
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import os
from typing import Dict, Optional
import asyncio
from datetime import datetime, timedelta

# 存储验证码的字典（生产环境应该使用Redis等持久化存储）
verification_codes: Dict[str, Dict[str, any]] = {}

# 清理过期验证码的定时任务
async def cleanup_expired_codes():
    while True:
        try:
            current_time = datetime.now()
            expired_emails = []
            
            for email, code_info in verification_codes.items():
                if code_info['expires_at'] < current_time:
                    expired_emails.append(email)
            
            for email in expired_emails:
                del verification_codes[email]
        except Exception as e:
            pass
        
        # 每5分钟清理一次
        await asyncio.sleep(300)


# SMTP 配置
SMTP_SERVER = "smtp.qq.com"
SMTP_PORT = 587
SMTP_USER = os.getenv("EMAIL_USER", "yu3466@qq.com")  # 使用环境变量
SMTP_PASSWORD = os.getenv("EMAIL_PASSWORD", "bohuhwddlbowcide")  # 应用专用密码


def send_email(to_email: str, code: str):
    """发送验证码邮件"""
    msg = MIMEText(f"您的验证码是: {code}\n请在 5 分钟内使用。", 'plain', 'utf-8')
    msg['Subject'] = Header('验证码验证', 'utf-8')
    msg['From'] = SMTP_USER
    msg['To'] = to_email

    try:
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()  # 启用 TLS
        server.login(SMTP_USER, SMTP_PASSWORD)
        server.send_message(msg)
        server.quit()
        return True
    except Exception as e:
        return False
